package com.promise.jokerdream.model.log

import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.serialization.Serializable

/**
 * 执行记录数据模型
 */
@Entity(tableName = "execution_log")
@Serializable
data class ExecutionLog(
    // 日志唯一ID
    @PrimaryKey
    val id: String = "",
    // 用户ID
    val userId: String = "",
    // 时间戳
    val timestamp: Long = System.currentTimeMillis(),
    // 操作类型（如：获取背包、好友列表等）
    val operation: String = "",
    // 响应消息
    val message: String = "",
    // 请求结果状态
    val result: Int = 0,
    // 额外信息（可选）
    val extra: String = ""
) {
    /**
     * 格式化时间显示
     * 今天显示"今天 HH:mm"，昨天显示"昨天 HH:mm"，其他显示"MM-dd HH:mm"
     */
    fun getFormattedTime(): String {
        val now = System.currentTimeMillis()
        val date = java.util.Date(timestamp)
        val today = java.util.Date(now)
        val yesterday = java.util.Date(now - 24 * 60 * 60 * 1000)
        
        val calendar = java.util.Calendar.getInstance()
        val logCalendar = java.util.Calendar.getInstance()
        logCalendar.time = date
        
        // 获取今天的年月日
        calendar.time = today
        val todayYear = calendar.get(java.util.Calendar.YEAR)
        val todayMonth = calendar.get(java.util.Calendar.MONTH)
        val todayDay = calendar.get(java.util.Calendar.DAY_OF_MONTH)
        
        // 获取昨天的年月日
        calendar.time = yesterday
        val yesterdayYear = calendar.get(java.util.Calendar.YEAR)
        val yesterdayMonth = calendar.get(java.util.Calendar.MONTH)
        val yesterdayDay = calendar.get(java.util.Calendar.DAY_OF_MONTH)
        
        // 获取日志的年月日
        val logYear = logCalendar.get(java.util.Calendar.YEAR)
        val logMonth = logCalendar.get(java.util.Calendar.MONTH)
        val logDay = logCalendar.get(java.util.Calendar.DAY_OF_MONTH)
        
        val timeFormat = java.text.SimpleDateFormat("HH:mm", java.util.Locale.getDefault())
        val dateFormat = java.text.SimpleDateFormat("MM-dd HH:mm", java.util.Locale.getDefault())
        
        return when {
            // 今天
            logYear == todayYear && logMonth == todayMonth && logDay == todayDay -> {
                "今天 ${timeFormat.format(date)}"
            }
            // 昨天
            logYear == yesterdayYear && logMonth == yesterdayMonth && logDay == yesterdayDay -> {
                "昨天 ${timeFormat.format(date)}"
            }
            // 其他日期
            else -> {
                dateFormat.format(date)
            }
        }
    }
    
    /**
     * 获取状态描述
     */
    fun getStatusText(): String {
        return when (result) {
            1 -> "成功"
            0 -> "失败"
            else -> "未知($result)"
        }
    }
}
